package time.after.time.sys;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;

import com.google.common.collect.Maps;


/**
 * 
 * 系统环境变量 Resource (顺序修改为从上至下)
 * 
 */
public class ConstHolder extends PropertyPlaceholderConfigurer {

	private static Map<String,String> consts=Maps.newHashMap();
	
	@Override
	public void setLocations(Resource[] locations) 
	{
		List<Resource> existResourceList = new ArrayList<Resource>();
		for(int i = 0; i < locations.length; i++) 
		{
			Resource resource = locations[i];
			if (resource.exists())
				existResourceList.add(resource);
		}
		// 优先顺序为由上至下
		Collections.reverse(existResourceList);
		Resource[] existResource = new Resource[existResourceList.size()];
		super.setLocations(existResourceList.toArray(existResource));
		for(Resource resource : existResource) 
		{
		   initProperties(resource);
		}
	}

	public void initProperties(Resource sysEnvResource)
	{
		Properties properties=new Properties();
		try
		{
			URL urlP = sysEnvResource.getURL();
			InputStream is = urlP.openStream();
			properties.load(is);
	    	is.close();
	    	Set<Entry<Object, Object>> sets=properties.entrySet();
	    	for(Entry<Object, Object> entry : sets) 
	    	{
	    		consts.put(entry.getKey().toString(), entry.getValue().toString());
			}
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}

	public static String get(String key)
	{
		return consts.get(key);
	}
}
